package com.jkc.xh.fragments;


import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jkc.xh.R;
import com.jkc.xh.fragments.core.BaseFragment;
import com.jkc.xh.manager.MoneyManager;
import com.jkc.xh.manager.UserManager;
import com.jkc.xh.models.BankModel;
import com.jkc.xh.models.BankSubModel;
import com.jkc.xh.models.BindBankCardModel;
import com.jkc.xh.models.CityModel;
import com.jkc.xh.models.ProvinceModel;
import com.jkc.xh.models.SmsListInfo;
import com.jkc.xh.network.RestCallBack;
import com.jkc.xh.network.models.BankListResponse;
import com.jkc.xh.network.models.BankSubListResponse;
import com.jkc.xh.network.models.BindCardRequest;
import com.jkc.xh.network.models.CityListResponse;
import com.jkc.xh.network.models.GetSmsListResponse;
import com.jkc.xh.network.models.ProvinceListResponse;
import com.jkc.xh.network.models.RestError;
import com.jkc.xh.views.widget.NavBar;
import com.jkc.xh.views.widget.ToastUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;

/**
 * 添加信用卡
 */
@SuppressWarnings("ResourceType")
@EFragment(R.layout.fragment_add_creditcrad)
public class AddCreditCradFragment extends BaseFragment {

    @ViewById(R.id.nav_bar)
    NavBar nav_bar;
    @ViewById
    TextView selectedBankName;
    @ViewById
    TextView selectedProvinceName;
    @ViewById
    TextView selectedCityName;
    @ViewById
    TextView selectedBankAddressName;
    @ViewById
    EditText inputCradNumber;
    @ViewById
    EditText inputRealName;
    @ViewById
    EditText inputIdCardNum;
    @ViewById
    EditText inputPhone;
    @ViewById
    EditText inputRadomNum;
    @ViewById
    RadioGroup smsRgGroup;
    @ViewById
    TextView getSmsCodeView;
    private BindBankCardModel card;
    private ArrayList<SmsListInfo> list;
    private long selectSmsId = -1;
    private ArrayList<BankModel> bankList;
    private long selectBankId = -1;
    private ArrayList<ProvinceModel> provinceList;
    private long selectProvinceId = -1;
    private ArrayList<CityModel> cityList;
    private long selectCityId = -1;
    private ArrayList<BankSubModel> bankSubList;
    private long selectBankSubId = -1;

    @AfterViews
    void initData() {
        nav_bar.setOnMenuClickListener(new NavBar.OnMenuClickListener() {
            @Override
            public void onLeftMenuClick(View view) {
                finishFragment();
            }
        });

        inputPhone.setText(UserManager.getMobile());
        inputPhone.setEnabled(false);
        showProgress();
        smsRgGroup.removeAllViews();
        smsRgGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                try {
                    selectSmsId = (Long) group.findViewById(checkedId).getTag();
                } catch (Exception e) {

                }

            }
        });

        addJob(MoneyManager.getBankList(new RestCallBack<BankListResponse>() {
            @Override
            public void success(BankListResponse bankListResponse) {
                bankList = bankListResponse.list;
                loadBankName();
            }

            @Override
            public void failure(RestError error) {

            }
        }));

        addJob(MoneyManager.getProvinceList(new RestCallBack<ProvinceListResponse>() {
            @Override
            public void success(ProvinceListResponse provinceListResponse) {
                hideProgress();
                provinceList = provinceListResponse.list;
                loadProvinceInfo();
            }

            @Override
            public void failure(RestError error) {
                hideProgress();
            }
        }));

        addJob(UserManager.getSmsSvrList(new RestCallBack<GetSmsListResponse>() {
            @Override
            public void success(GetSmsListResponse response) {
                if (response.list == null || response.list.size() == 0) {
                    return;
                }
                list = response.list;
                for (SmsListInfo tmp : list) {
                    smsRgGroup.addView(getSmsRadioButton(tmp.name, tmp.smsid));
                }
                smsRgGroup.check(1);
            }

            @Override
            public void failure(RestError error) {

            }
        }));


        addJob(MoneyManager.getBindCardInfo(new RestCallBack<BindBankCardModel>() {
            @Override
            public void success(BindBankCardModel bindBankCardResponse) {
                card = bindBankCardResponse;
                if (card == null) {
                    return;
                }
                loadCurrentCardInfo();
            }

            @Override
            public void failure(RestError error) {

            }
        }));
    }

    private void loadCurrentCardInfo() {
        if (card == null) {
            return;
        }
        //加载银行信息
        loadBankName();
        loadBankSubName();
        //加载省份
        loadProvinceInfo();
        inputIdCardNum.setText(card.idno);
        inputCradNumber.setText(card.cardno);
        inputRealName.setText(card.cardname);
        if (!TextUtils.isEmpty(card.cardname)) {
            inputRealName.setEnabled(false);
        }
    }

    /**
     * 加载银行信息
     */
    private void loadBankName() {
        if (bankList != null && card != null) {
            for (BankModel bank : bankList) {
                if (bank.bank_id == card.bank_id) {
                    selectedBankName.setText(bank.name);
                    selectBankId = card.bank_id;
                    break;
                }
            }
        }
    }

    /**
     * 加载省份
     */
    private void loadProvinceInfo() {
        if (provinceList != null && card != null) {
            for (ProvinceModel model : provinceList) {
                if (model.prov_cd == card.prov_cd) {
                    selectedProvinceName.setText(model.prov_nm);
                    selectProvinceId = model.prov_cd;
                    loadCityInfo();
                    break;
                }
            }
        }
    }

    /**
     * 加载城市
     */
    private void loadCityInfo() {
        if (card != null) {
            if (cityList != null) {
                for (CityModel model : cityList) {
                    if (model.city_cd == card.city_cd) {
                        selectedCityName.setText(model.city_nm);
                        selectCityId = model.city_cd;
                        break;
                    }
                }
            } else {
                addJob(MoneyManager.getCityList(selectProvinceId, new RestCallBack<CityListResponse>() {
                    @Override
                    public void success(CityListResponse response) {
                        hideProgress();
                        cityList = response.list;
                        loadCityInfo();
                    }

                    @Override
                    public void failure(RestError error) {
                        hideProgress();
                    }
                }));
            }
        }
    }

    private void loadBankSubName() {
        if (card != null) {
            selectBankSubId = card.sub_id;
            selectedBankAddressName.setText(card.sub_name);
        }
    }

    private RadioButton getSmsRadioButton(String name, long smsId) {
        RadioButton tempButton = new RadioButton(getActivity());
        tempButton.setButtonDrawable(R.drawable.selector_radiobox_red);
        tempButton.setText(name);
        tempButton.setTag(smsId);
        return tempButton;
    }

    @Click(R.id.selectBankView)
    void showBankList() {
        if (bankList == null || bankList.size() <= 0) {
            return;
        }
        String[] bankListValue = new String[bankList.size()];
        for (int index = 0; index < bankList.size(); index++) {
            bankListValue[index] = bankList.get(index).name;
        }
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()).setTitle("请选择银行");
        dialogBuilder.setSingleChoiceItems(bankListValue, -1, new DialogInterface.OnClickListener(
        ) {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                selectedBankName.setText(bankList.get(which).name);
                if (selectBankId != bankList.get(which).bank_id) {
                    clearBankSubInfo();
                }
                selectBankId = bankList.get(which).bank_id;
            }
        });
        dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    @Click(R.id.selectBankAddressView)
    void showBankAddressList() {
        showProgress();
        bankSubList = null;
        if (selectCityId > 0 && selectBankId > 0) {
            addJob(MoneyManager.getSubBankList(selectBankId, selectCityId, new RestCallBack<BankSubListResponse>() {
                @Override
                public void success(BankSubListResponse response) {
                    hideProgress();
                    bankSubList = response.list;
                    showBankSubSelectDialog();
                }

                @Override
                public void failure(RestError error) {
                    hideProgress();
                }
            }));
        } else {
            ToastUtil.showToastShort("请先选择银行跟所在城市");
        }
    }

    @Click(R.id.selectProvinceView)
    void showProvinceList() {
        if (provinceList == null || provinceList.size() <= 0) {
            return;
        }
        String[] listValue = new String[provinceList.size()];
        for (int index = 0; index < provinceList.size(); index++) {
            listValue[index] = provinceList.get(index).prov_nm;
        }
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()).setTitle("请选择省份");
        dialogBuilder.setSingleChoiceItems(listValue, -1, new DialogInterface.OnClickListener(
        ) {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                selectedProvinceName.setText(provinceList.get(which).prov_nm);
                if (selectProvinceId != provinceList.get(which).prov_cd) {
                    clearCityInfo();
                    clearBankSubInfo();
                }
                selectProvinceId = provinceList.get(which).prov_cd;
            }
        });
        dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    @Click(R.id.selectCityView)
    void showCityList() {
        showProgress();
        cityList = null;
        if (selectProvinceId > 0) {
            addJob(MoneyManager.getCityList(selectProvinceId, new RestCallBack<CityListResponse>() {
                @Override
                public void success(CityListResponse response) {
                    hideProgress();
                    cityList = response.list;
                    loadCityInfo();
                    showCitySelectDialog();
                }

                @Override
                public void failure(RestError error) {
                    hideProgress();
                }
            }));
        } else {
            ToastUtil.showToastShort("请选择城市");
        }
    }

    private void showCitySelectDialog() {
        if (cityList == null || cityList.size() <= 0) {
            return;
        }
        String[] listValue = new String[cityList.size()];
        for (int index = 0; index < cityList.size(); index++) {
            listValue[index] = cityList.get(index).city_nm;
        }
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()).setTitle("请选择银行");
        dialogBuilder.setSingleChoiceItems(listValue, -1, new DialogInterface.OnClickListener(
        ) {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                selectedCityName.setText(cityList.get(which).city_nm);
                selectCityId = cityList.get(which).city_cd;
            }
        });
        dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    private void showBankSubSelectDialog() {
        if (bankSubList == null || bankSubList.size() <= 0) {
            return;
        }
        String[] listValue = new String[bankSubList.size()];
        for (int index = 0; index < bankSubList.size(); index++) {
            listValue[index] = bankSubList.get(index).sub_name;
        }
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity()).setTitle("请选择支行");
        dialogBuilder.setSingleChoiceItems(listValue, -1, new DialogInterface.OnClickListener(
        ) {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                selectedBankAddressName.setText(bankSubList.get(which).sub_name);
                selectBankSubId = bankSubList.get(which).sub_id;
            }
        });
        dialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialogBuilder.create().show();
    }

    private void clearBankSubInfo() {
        selectedBankAddressName.setText("");
        selectBankSubId = -1;
    }

    private void clearCityInfo() {
        selectedCityName.setText("");
        selectCityId = -1;
    }


    @Click(R.id.getSmsCodeView)
    void getSmsCode() {
        String mobile = inputPhone.getText().toString();
        if (TextUtils.isEmpty(mobile) || mobile.length() != 11) {
            ToastUtil.showToastShort("请输入正确的手机号码");
            return;
        }
        showProgress("获取验证码中");
        UserManager.getSmsCode(mobile, 5, selectSmsId, new RestCallBack<Object>() {
            @Override
            public void success(Object o) {
                hideProgress();
                timer.start();
                ToastUtil.showToastShort("短信发送成功.请注意查收");
            }

            @Override
            public void failure(RestError error) {
                hideProgress();
                timer.cancel();
            }
        });
    }
    /**
     * 倒计时
     */
    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            long time = millisUntilFinished / 1000;
            getSmsCodeView.setText("再次获取(" + time + "s)");
            getSmsCodeView.setClickable(false);
//            getSmsCodeView.setBackgroundResource(R.drawable.round_gray_normal_m_radius);
        }

        @Override
        public void onFinish() {
            getSmsCodeView.setText("再次获取");
            getSmsCodeView.setClickable(true);
//            getSmsCodeView.setBackgroundResource(R.drawable.xml_green_btn_selector_m);
        }
    };
    @Click(R.id.btnSave)
    void bindBankCard() {
        if (selectBankSubId < 0) {
            ToastUtil.showToastShort("请选择银行卡支行");
            return;
        }
        String cardNumber = inputCradNumber.getText().toString();
        if (TextUtils.isEmpty(cardNumber) || cardNumber.length() < 10) {
            ToastUtil.showToastShort("请输入正确的银行卡号码");
            return;
        }
        String realName = inputRealName.getText().toString();
        if (TextUtils.isEmpty(realName)) {
            ToastUtil.showToastShort("请输入户名");
            return;
        }
        String idNum = inputIdCardNum.getText().toString();
        if (TextUtils.isEmpty(idNum)) {
            ToastUtil.showToastShort("请输入身份证号码");
            return;
        }
        String mobile = inputPhone.getText().toString();
        if (TextUtils.isEmpty(mobile) || mobile.length() != 11) {
            ToastUtil.showToastShort("请输入正确的手机号码");
            return;
        }

        String smsCode = inputRadomNum.getText().toString();
        if (TextUtils.isEmpty(smsCode) || smsCode.length() != 6) {
            ToastUtil.showToastShort("请输入短信验证码");
            return;
        }
        BindCardRequest request = new BindCardRequest(selectBankSubId, cardNumber, realName, idNum, mobile, smsCode);
        showProgress("正在绑定银行卡");
        addJob(MoneyManager.bindCard(request, new RestCallBack<Object>() {
            @Override
            public void success(Object o) {
                hideProgress();
                ToastUtil.showToastShort("绑定银行卡成功");
            }

            @Override
            public void failure(RestError error) {
                hideProgress();
                ToastUtil.showToastShort(error.msg);
            }
        }));
    }
}
